package com.cooldatasoft.web.product.main;

import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;

import com.cooldatasoft.app.ProductApplication;
import com.cooldatasoft.app.WOCApplication;
import com.cooldatasoft.data.Node;
import com.cooldatasoft.menu.NodeBox;
import com.cooldatasoft.web.cms.main.AdminOrganizationChart;
import com.cooldatasoft.web.product.error.ErrorPage;

public class OrganizationChart extends WebPage {

	public OrganizationChart() {
		this(1);
	}

	public OrganizationChart(final Integer rootNodeId) {
		

		if(rootNodeId == 1){
			List<Node> nodeList = ProductApplication.get().getNodeServiceProxy().getChildrenNodeList(rootNodeId);
			if(nodeList == null || nodeList.size() == 0){
				setResponsePage(new ErrorPage("Please insert person to database before using"));
				return;
			}else if(nodeList.size() == 1){
				//Normally the list should contain only one element other than default root.
				initPage(nodeList.get(0).getId());
				return;
			}else{
				//Eger bu kısma gelirse CEO kısmında 1den fazla insan var demktir o zmn ona gore
				//gostermesi gerekli simdilik CEO nun tek kisi oldugunu farzediyorum.
				setResponsePage(new ErrorPage("Only one person can be Head of the company "));
				return;
			}
		}
		
		initPage(rootNodeId);
		

	}

	private void initPage(final Integer rootNodeId) {
		
		//Repeater with td
		List<Node> childrenNodeList = ProductApplication.get().getNodeServiceProxy().getChildrenNodeList(rootNodeId);
		boolean isLeafNode=false;
		if(childrenNodeList.size()==0){
			isLeafNode = true;
		}
		
		Link homeLink = new Link("homeLink") {
			@Override
			public void onClick() {
				if(rootNodeId==1){
					return;
				}
				setResponsePage(new AdminOrganizationChart());
			}
		}; 		
		add(homeLink);
		
		
		Link parentLink = new Link("parentLink") {
			@Override
			public void onClick() {
				if(rootNodeId==1){
					return;
				}
				Node rootNode = WOCApplication.get().getNodeServiceProxy().get(rootNodeId);
				setResponsePage(new AdminOrganizationChart(rootNode.getParentId()));
			}
		}; 		
		add(parentLink);
		
		NodeBox rootNodeBox = new NodeBox("rootNodeBox",rootNodeId,isLeafNode);
		rootNodeBox.setOutputMarkupId(true);
		add(rootNodeBox);
	
		
		
		ListView childrenNodeBoxes = new ListView("childrenNodeBoxes", childrenNodeList) {
		    protected void populateItem(ListItem item) {
		       final Node currentNode = (Node) item.getModelObject();
		       NodeBox nodeBox = new NodeBox("memberNodeBox",currentNode.getId(),true);
		       nodeBox.setOutputMarkupId(true);
		       item.add(nodeBox);				
		    }
		};
		add(childrenNodeBoxes);
		
//		add(HeaderContributor.forCss("css/nodeBox.css"));

	}

}
